<script setup lang='ts'>
//引入ref
import { ref } from 'vue'
//引入store
import {useUserStore} from '@/stores/users'
//使用路由进行跳转
import { useRouter } from 'vue-router';
const router = useRouter()
//使用仓库
const userStore = useUserStore()
//编写正则
const pattern = /^\d{5}$/
//是否禁用的按钮
let disab = ref(false)
//输入的验证码
const code = ref('');
const code1 = ref('');
const onSubmit = async (values: object) => {
    if(code1.value == code.value){
        //发送验证码
        try{
            await userStore.checkCodeHandler({tel:userStore.loginname,telcode:code.value})
            router.push("/register/step3")
        }catch{
            router.push("/register")
        }
    }
};

let buttonMsg:any = ref("发送验证码")
//点击验证码
const getCheckCode = async () =>{
    //倒计时从60s开始
    let num = 60;
    //禁用按钮
    disab.value = true;
    setInterval(()=>{
        buttonMsg.value = `${num--}s再次发送`
        if(num <= 0){
            buttonMsg.value = "发送验证码"
            disab.value = false;
        }
    },1000)
    //发送请求,获取验证码
    const result = await userStore.getCheckCode({tel:userStore.loginname})
    code.value = result
    code1.value = result
}

</script>
<template>
    <van-form @submit="onSubmit" validate-trigger="onChange">
        <van-cell-group inset>
            <van-field v-model="code" name="code" label="短信验证码" placeholder="请输入短信验证码" :rules="[{ required: true, message: '请填写用户名' },{pattern,message:'验证码长度为5位'}]">
                <!-- 具名插槽 -->
                <template #button>
                    <van-button round size="small" :disabled="disab" type="danger" @click="getCheckCode">{{buttonMsg}}</van-button>
                </template>
            </van-field>
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="danger" native-type="submit">
                下一步
            </van-button>
        </div>
    </van-form>
</template>
<style scoped lang='scss'>
.van-form {
    margin-top: 60px;
}
</style>